#include "emergency_ctrl.h"
#include "elog.h"

#include "charge_mem_tab.h"
#include "cmd_map_rw.h"

static int emergency_state = EMERGENCY_INIT;
/**
 * @brief   急停按键初始化
 * @return  int
 */
int emergency_ctrl_pin_init(void)
{
    rt_pin_mode(EMERGENCY_PIN, PIN_MODE_INPUT_PULLDOWN);
    log_d("emergency pin init success.");
    return 0;
}
INIT_APP_EXPORT(emergency_ctrl_pin_init);

/**
 * @brief                   急停控制
 * @param  emerg            Function Param doc
 * @return int
 */
int emergency_ctrl_fsm(app_t *emerg)
{
    int ret = 0;
    static uint32_t tick = 0;
    uint32_t charge_state = 0;

    switch (emergency_state)
    {
    case EMERGENCY_INIT:
        general_cmd_map_get(CMD_MAP_CHARGE, CHARGE_STATE, (uint8_t *)&charge_state, 4u);
        if (charge_state)
        {
            tick = xTaskGetTickCount();
            emergency_state = EMERGENCY_WAIT;
        }
        break;
    case EMERGENCY_WAIT:
        if (xTaskGetTickCount() - tick >= EMERGENCY_KEY_TIMEOUT)
        {
            emergency_state = EMERGENCY_START;
        }
        else
        {
            if (!rt_pin_read(EMERGENCY_PIN))
                emergency_state = EMERGENCY_INIT;
        }
        break;
    case EMERGENCY_START:
        emerg->status = CHARGE_END_STATE;
        emergency_state = EMERGENCY_END;
        break;
    case EMERGENCY_END:
        if (!rt_pin_read(EMERGENCY_PIN))
            emergency_state = EMERGENCY_INIT;
        break;
    default:
        break;
    }
    return ret;
}
